//
//  CommentsController.swift
//  App
//
//  Created by melvyn on 2018/9/13.
//

import Foundation
import Vapor

class CommentsController: RouteCollection {
    
    func boot(router: Router) throws {
        
        let noAuth = router.grouped("comments")
        noAuth.get(Comment.parameter, use: find)
        
        let bearer = noAuth.grouped(User.tokenAuthMiddleware())
        bearer.post(use: create)
    }
    
    func create(_ req: Request) throws -> EventLoopFuture<Comment> {
        let user = try req.requireAuthenticated(User.self)
        return try req.content.decode(Comment.self)
            .map({
                var model = $0
                model.uid = user.id
                return model
            })
            .save(on: req)
    }

    func find(_ req: Request) throws -> EventLoopFuture<Comment> {
        return try req.parameters.next(Comment.self)
    }
}
